﻿using AutoMapper;
using Entity.WMS.DTO.WarehousePurchase;
using Entity.WMS.View.WarehousePurchase;
using FrameWork.DataContext;
using FrameWork.DataHelper;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace Service.WMS
{
    public class WarehousePurchaseService
    {
        /**
         * 数据库上下文
         */
        private readonly DataContext _context;

        /**
         * 自动映射器
         */
        private readonly IMapper _mapper;

        /**
         * 构造函数注入
         */
        public WarehousePurchaseService(DataContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /**
         * 获取采购入库单列表
         */
        public async Task<RequestResponseModel<PageResult<WarehousePurchaseView>>> GetWarehousePurchaseList(WarehousePurchaseSearchDTO warehousePurchaseSearchDTO)
        {
            // 筛选
            var query = _context.WarehousePurchaseView
                .WhereIF(a => a.CardNo.Contains(warehousePurchaseSearchDTO.CardNo), !string.IsNullOrEmpty(warehousePurchaseSearchDTO.CardNo))
                .WhereIF(a => a.GoodsCode.Contains(warehousePurchaseSearchDTO.Goods) || a.GoodsName.Contains(warehousePurchaseSearchDTO.Goods) || a.GoodsSpec.Contains(warehousePurchaseSearchDTO.Goods), !string.IsNullOrEmpty(warehousePurchaseSearchDTO.Goods))
                .WhereIF(a => a.WarehouseCode.Contains(warehousePurchaseSearchDTO.Warehouse) || a.WarehouseName.Contains(warehousePurchaseSearchDTO.Warehouse), !string.IsNullOrEmpty(warehousePurchaseSearchDTO.Warehouse))
                .WhereIF(a => a.WarehousePositionCode.Contains(warehousePurchaseSearchDTO.WarehousePosition) || a.WarehousePositionName.Contains(warehousePurchaseSearchDTO.WarehousePosition), !string.IsNullOrEmpty(warehousePurchaseSearchDTO.WarehousePosition))
                ;

            // 返回列表
            var warehousePurchaseList = await query
                .OrderBy(a => a.CreateTime)
                .Page(warehousePurchaseSearchDTO.CurrentPage, warehousePurchaseSearchDTO.PageSize)
                .ToListAsync();

            // 计算总数
            var pageCount = await query.CountAsync();

            // 返回数据
            var pageResult = new PageResult<WarehousePurchaseView>(warehousePurchaseList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }
    }
}
